﻿using Main.DataBaseContext;
using Main.dto;
using Main.messageEvent;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Input;

namespace Main.ViewModels
{
	public class AddMemoDialogViewModel : BindableBase,IDialogAware
	{
        private readonly BusnessContext busnessContext;
        private readonly IEventAggregator eventAggregator;

        private ToDoTask ToDoTask { get; set; }

        public ICommand ExecuteAddingMemo { get; set; }

        private ICommand CloseDialog { get; set; }

        public ObservableCollection<ToDoTask> toDoTasks { get; set; } = new ObservableCollection<ToDoTask>();

        public string MemoContent { get; set; }

        public AddMemoDialogViewModel(BusnessContext busnessContext,IEventAggregator eventAggregator)
        {
            ExecuteAddingMemo = new DelegateCommand(ExecuteAddingMemoHandler);
            CloseDialog = new DelegateCommand(() => {

                RequestClose?.Invoke(new DialogResult(ButtonResult.Cancel));
            });
            this.busnessContext = busnessContext;
            this.eventAggregator = eventAggregator;
        }

        public string Title => "添加备忘录";

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
            
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            if(parameters.TryGetValue("toDoTask",out ToDoTask toDoTask)){

                ToDoTask = toDoTask;
                toDoTasks .Clear();
                toDoTasks.Add(toDoTask);


            }
        }

        private async void ExecuteAddingMemoHandler() {

            if (string.IsNullOrWhiteSpace(MemoContent)) {
                MessageBox.Show("请输入有效的备忘录内容");
                return;
            }

            /*
             * 因为 busnessContext.ToDoTasks 中已经存在同id 的 ToDoTask
             * 所以这样额外添加一个相同id的 ToDoTask 将会抛出异常
             * ToDoTask toDoTask = new ToDoTask() {
                Id = ToDoTask.Id,
                Memos = new List<Memo>() {
                    new Memo()
                    {   
                        Content = MemoContent
                    }
                }
            };

            busnessContext.ToDoTasks.Add(toDoTask);*/


            ToDoTask.Memos.Add(new Memo()
            {
                Content = MemoContent
            });

            await busnessContext.SaveChangesAsync();

            eventAggregator.GetEvent<RefreshMainWindowEvent>().Publish("");

            RequestClose?.Invoke(new DialogResult(ButtonResult.OK));
        }
    }
}
